package org.java.net.socket;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;
import java.io.*;

public class Client5 extends Frame implements Runnable{

	private TextField nameBox=new TextField("<名字>");
	private TextArea msgView=new TextArea();
	private TextField sendBox=new TextField();
	private BufferedReader reader;
	private PrintWriter writer;
	private Socket socket;
	  
	public Client5(String title)
	{
		super(title);
		msgView.setEditable(false);
		
	    add(nameBox,"North");
	    add(msgView,"Center");
	    add(sendBox,"South");
	    
	    sendBox.addActionListener(new ActionListener(){
	        public void actionPerformed(ActionEvent ae){
	          try{
	            writer.println(nameBox.getText()+" : "+ sendBox.getText());
	            sendBox.setText("");
	          }catch(Exception ie){}
	        }
	      });
	      pack();
	}
	
	public void run()
	{
		while(true)
		{
			try
			{
				msgView.append(reader.readLine()+"\n");
			}
			catch(IOException ie)
			{}
		}
	}
	
	private void connect()
	{
		try
		{
			msgView.append("尝试与服务器套接字连接");
			socket = new Socket("127.0.0.1", 7777);
			msgView.append("连天准备完毕\n");
			
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			writer = new PrintWriter(socket.getOutputStream(), true);
			new Thread(this).start();
		}
		catch(Exception e)
		{
			msgView.append("连接失败...");
		}
	}
	
	public static void main(String[] args)
	{
		Client5 client=new Client5("聊天");
	    client.setVisible(true);
	    client.connect();
	}
}
